/*
 * 入库单多表联查控制器
 * 用于查询入库单主表和明细表的联合数据
 */
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Threading.Tasks;
using VOL.Core.Utilities;
using VOL.Entity.DomainModels;
using VOL.demo.IServices;

namespace VOL.demo.Controllers
{
    /// <summary>
    /// 入库单多表联查控制器
    /// </summary>
    [Route("api/ruku")]
    [ApiController]
    [AllowAnonymous]  // 允许匿名访问，不需要JWT验证
    public class RukuController : ControllerBase
    {
        private readonly IRukuService _rukuService;

        public RukuController(IRukuService rukuService)
        {
            _rukuService = rukuService;
        }

        /// <summary>
        /// 根据ID获取入库单详情（主表+明细）
        /// </summary>
        /// <param name="id">入库单ID</param>
        /// <returns>入库单详情</returns>
        [HttpGet("detail/{id}")]
        public async Task<ActionResult> GetRukuDetailById(long id)
        {
            try
            {
                var result = await _rukuService.GetRukuDetailByIdAsync(id);

                if (result == null)
                {
                    return NotFound(new
                    {
                        success = false,
                        message = "入库单不存在"
                    });
                }

                return Ok(new
                {
                    success = true,
                    message = "获取入库单详情成功",
                    data = result
                });
            }
            catch (Exception ex)
            {
                return BadRequest(new
                {
                    success = false,
                    message = $"获取入库单详情失败：{ex.Message}"
                });
            }
        }

        /// <summary>
        /// 根据入库单号获取详情
        /// </summary>
        /// <param name="code">入库单号</param>
        /// <returns>入库单详情</returns>
        [HttpGet("detail/code/{code}")]
        public async Task<ActionResult> GetRukuDetailByCode(string code)
        {
            try
            {
                var result = await _rukuService.GetRukuDetailByCodeAsync(code);

                if (result == null)
                {
                    return NotFound(new
                    {
                        success = false,
                        message = "入库单不存在"
                    });
                }

                return Ok(new
                {
                    success = true,
                    message = "获取入库单详情成功",
                    data = result
                });
            }
            catch (Exception ex)
            {
                return BadRequest(new
                {
                    success = false,
                    message = $"获取入库单详情失败：{ex.Message}"
                });
            }
        }

        /// <summary>
        /// 分页查询入库单列表（主表+明细统计）
        /// </summary>
        /// <param name="query">查询参数</param>
        /// <returns>分页结果</returns>
        [HttpPost("list")]
        public async Task<ActionResult> GetRukuPagedList([FromBody] RukuQueryDto query)
        {
            try
            {
                if (query == null)
                {
                    query = new RukuQueryDto();
                }

                var (data, totalCount) = await _rukuService.GetRukuPagedListAsync(query);

                return Ok(new
                {
                    success = true,
                    message = "获取入库单列表成功",
                    data = data,
                    totalCount = totalCount,
                    pageIndex = query.PageIndex,
                    pageSize = query.PageSize,
                    totalPages = (int)Math.Ceiling((double)totalCount / query.PageSize)
                });
            }
            catch (Exception ex)
            {
                return BadRequest(new
                {
                    success = false,
                    message = $"获取入库单列表失败：{ex.Message}"
                });
            }
        }

        /// <summary>
        /// 分页查询入库单列表（GET方式，用于简单查询）
        /// </summary>
        /// <param name="pageIndex">页码，默认1</param>
        /// <param name="pageSize">每页记录数，默认20</param>
        /// <param name="stockInCode">入库单号</param>
        /// <param name="warehouseId">仓库ID</param>
        /// <param name="supplierId">供应商ID</param>
        /// <param name="status">单据状态</param>
        /// <param name="keyword">关键词</param>
        /// <returns>分页结果</returns>
        [HttpGet("list")]
        public async Task<ActionResult> GetRukuPagedListGet(
            int pageIndex = 1,
            int pageSize = 20,
            string stockInCode = null,
            long? warehouseId = null,
            long? supplierId = null,
            int? status = null,
            string keyword = null)
        {
            try
            {
                var query = new RukuQueryDto
                {
                    PageIndex = pageIndex,
                    PageSize = pageSize,
                    StockInCode = stockInCode,
                    WarehouseId = warehouseId,
                    SupplierId = supplierId,
                    Status = status,
                    Keyword = keyword
                };

                var (data, totalCount) = await _rukuService.GetRukuPagedListAsync(query);

                return Ok(new
                {
                    success = true,
                    message = "获取入库单列表成功",
                    data = data,
                    totalCount = totalCount,
                    pageIndex = pageIndex,
                    pageSize = pageSize,
                    totalPages = (int)Math.Ceiling((double)totalCount / pageSize)
                });
            }
            catch (Exception ex)
            {
                return BadRequest(new
                {
                    success = false,
                    message = $"获取入库单列表失败：{ex.Message}"
                });
            }
        }

        /// <summary>
        /// 获取入库单统计信息
        /// </summary>
        /// <param name="startDate">开始日期</param>
        /// <param name="endDate">结束日期</param>
        /// <returns>统计信息</returns>
        [HttpGet("statistics")]
        public async Task<ActionResult> GetRukuStatistics(DateTime? startDate = null, DateTime? endDate = null)
        {
            try
            {
                var result = await _rukuService.GetRukuStatisticsAsync(startDate, endDate);

                return Ok(new
                {
                    success = true,
                    message = "获取统计信息成功",
                    data = result
                });
            }
            catch (Exception ex)
            {
                return BadRequest(new
                {
                    success = false,
                    message = $"获取统计信息失败：{ex.Message}"
                });
            }
        }

        /// <summary>
        /// 健康检查
        /// </summary>
        /// <returns></returns>
        [HttpGet("health")]
        public ActionResult Health()
        {
            return Ok(new
            {
                success = true,
                message = "入库单多表联查服务运行正常",
                timestamp = DateTime.Now
            });
        }

        /// <summary>
        /// 分页查询入库明细列表（POST）
        /// </summary>
        /// <param name="query">查询参数</param>
        /// <returns>分页结果</returns>
        [HttpPost("items/list")]
        public async Task<ActionResult> GetRukuItemPagedList([FromBody] RukuItemQueryDto query)
        {
            try
            {
                if (query == null)
                {
                    query = new RukuItemQueryDto();
                }

                var (data, totalCount) = await _rukuService.GetRukuItemPagedListAsync(query);

                return Ok(new
                {
                    success = true,
                    message = "获取入库明细列表成功",
                    data = data,
                    totalCount = totalCount,
                    pageIndex = query.PageIndex,
                    pageSize = query.PageSize,
                    totalPages = (int)Math.Ceiling((double)totalCount / query.PageSize)
                });
            }
            catch (Exception ex)
            {
                return BadRequest(new
                {
                    success = false,
                    message = $"获取入库明细列表失败：{ex.Message}"
                });
            }
        }

        /// <summary>
        /// 分页查询入库明细列表（GET方式，用于简单查询）
        /// </summary>
        /// <param name="pageIndex">页码，默认1</param>
        /// <param name="pageSize">每页记录数，默认20</param>
        /// <param name="stockInOrderId">入库单ID</param>
        /// <param name="stockInCode">入库单号</param>
        /// <param name="goodsId">货品ID</param>
        /// <param name="goodsCode">货品编号</param>
        /// <param name="goodsName">货品名称</param>
        /// <param name="batchNo">批次号</param>
        /// <param name="stockPosition">库位ID</param>
        /// <param name="keyword">关键词</param>
        /// <returns>分页结果</returns>
        [HttpGet("items/list")]
        public async Task<ActionResult> GetRukuItemPagedListGet(
            int pageIndex = 1,
            int pageSize = 20,
            long? stockInOrderId = null,
            string stockInCode = null,
            long? goodsId = null,
            string goodsCode = null,
            string goodsName = null,
            string batchNo = null,
            long? stockPosition = null,
            string keyword = null)
        {
            try
            {
                var query = new RukuItemQueryDto
                {
                    PageIndex = pageIndex,
                    PageSize = pageSize,
                    StockInOrderId = stockInOrderId,
                    StockInCode = stockInCode,
                    GoodsId = goodsId,
                    GoodsCode = goodsCode,
                    GoodsName = goodsName,
                    BatchNo = batchNo,
                    StockPosition = stockPosition,
                    Keyword = keyword
                };

                var (data, totalCount) = await _rukuService.GetRukuItemPagedListAsync(query);

                return Ok(new
                {
                    success = true,
                    message = "获取入库明细列表成功",
                    data = data,
                    totalCount = totalCount,
                    pageIndex = pageIndex,
                    pageSize = pageSize,
                    totalPages = (int)Math.Ceiling((double)totalCount / pageSize)
                });
            }
            catch (Exception ex)
            {
                return BadRequest(new
                {
                    success = false,
                    message = $"获取入库明细列表失败：{ex.Message}"
                });
            }
        }

        /// <summary>
        /// 根据入库单ID获取所有明细
        /// </summary>
        /// <param name="stockInOrderId">入库单ID</param>
        /// <returns>明细列表</returns>
        [HttpGet("items/order/{stockInOrderId}")]
        public async Task<ActionResult> GetRukuItemsByOrderId(long stockInOrderId)
        {
            try
            {
                var result = await _rukuService.GetRukuItemsByOrderIdAsync(stockInOrderId);

                return Ok(new
                {
                    success = true,
                    message = "获取入库明细成功",
                    data = result,
                    totalCount = result.Count
                });
            }
            catch (Exception ex)
            {
                return BadRequest(new
                {
                    success = false,
                    message = $"获取入库明细失败：{ex.Message}"
                });
            }
        }
    }
}

